//重写数组中的部分方法
//获取数组原型
let oldArrayProto = Array.prototype;

export let newArrayProto = Object.create(oldArrayProto);
//找到所有会改变原数组的的方法
let methods = ["push", "pop", "shift", "unshift", "reverse", "sort", "splice"];

methods.forEach((method) => {
  //重写数组的方法
  newArrayProto[method] = function (...args) {
    // 内部调用原来的方法，函数的劫持
    const result = oldArrayProto[method].call(this, ...args);
    let inserted;
    let ob = this.__ob__;
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
        break;
      default:
        break;
    }

    if (inserted) {
      ob.observeArray(inserted);
    }

    ob.dep.notify(); //数组变化，通知对应的watcher实现更新逻辑
    return result;
  };
});
